<script lang="ts" setup>
import { propTypes } from '@/utils/propTypes'

const emits = defineEmits(['iframeContent', 'iframeHeight']) // 定义 emits
defineOptions({ name: 'IFrame' })

const props = defineProps({
  src: propTypes.string.def('')
})
const loading = ref(true)
const frameRef = ref<HTMLElement | null>(null)
const init = () => {
  nextTick(() => {
    loading.value = true
    if (!frameRef.value) return
    frameRef.value.onload = () => {
      loading.value = false
    }
  })
}
onMounted(() => {
  init()
  window.addEventListener('message', handleMessage);
})
watch(
  () => props.src,
  () => {
    init()
  }
)
const threeUrl = import.meta.env.VITE_3D_URL;
//由iframe调用
const handleMessage = (event) => {
  // 确保消息来自预期的源
  if (event.origin !== threeUrl) {
    return;
  }
  //获取评审内容
  if (event.data && event.data.type === 'CALL_METHOD') {
    emits('iframeContent', event.data.payload.iframe, event.data.payload.modelId)
  }
  if (event.data && event.data.type === 'height') {
    // 设置 iframe 高度
    if (frameRef.value) {
      frameRef.value.style.height = event.data.payload.height + 'px';
      emits('iframeHeight', event.data.payload.height + 'px')
    }
  }
}
</script>
<template>
  <div
    v-loading="loading"
    class="w-full h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-var(--app-content-padding)-var(--app-content-padding)-2px)]"
  >
    <iframe
      ref="frameRef"
      :src="props.src"
      frameborder="0"
      scrolling="no"
      height="100%"
      width="100%"
      allowfullscreen="true"
      webkitallowfullscreen="true"
      mozallowfullscreen="true"
    ></iframe>
  </div>
</template>
